package com.cgx.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @author chenguanxin
 * @date 2021-06-27 03:11
 */
public class JwtUtils {

    private final static String SALT_KEY = "cgx_salt_key";

    public static String createJwt(String userId, String subject, long expire) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(userId)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, SALT_KEY)
                .setExpiration(new Date(nowMillis + expire));
        return builder.compact();
    }

    public static Claims parseJwt(String jwtStr){
        return  Jwts.parser()
                .setSigningKey(SALT_KEY)
                .parseClaimsJws(jwtStr)
                .getBody();
    }
}
